package com.topi.integration.transformer.helper;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.xml.transform.TransformerHelper;

public class MessageSourceConverterHelper {

	private static final Logger logger = Logger.getLogger(MessageSourceConverterHelper.class);
	
	private TransformerHelper transformerHelper;
	
	public MessageSourceConverterHelper() {
	
		transformerHelper = new TransformerHelper();
		
	}

	public void createFileToPayload(String fileName, Source source) throws TransformerException {
		Writer writer = null;
		try {
			
			writer = new BufferedWriter(new FileWriter( fileName ));
			
			Transformer transformer = createNonIndentingTransformer();

			transformer.transform(source, new StreamResult(writer));
			
			writer.flush();
			
		} catch (IOException e) {
			logger.error(e);
		} finally {
			IOUtils.closeQuietly(writer);
		}

	}
		
	
	public String convertToString(Source source) throws TransformerException {

		if (source == null)
			return "";

		Transformer transformer = createNonIndentingTransformer();
		StringWriter writer = new StringWriter();
		transformer.transform(source, new StreamResult(writer));

		return writer.toString();

	}	
	
	
	public Transformer createNonIndentingTransformer() throws TransformerConfigurationException {
		Transformer transformer = createTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		return transformer;
	}

	private final Transformer createTransformer() throws TransformerConfigurationException {
		return transformerHelper.createTransformer();
	}

	
}
